<template>
  <view class="page">
    <!-- <Head color="#ffffff" :title="` `" @rightClick="toUrl('/pages/my/withdrawalList')">
      <text slot="right" style="color: #ffffff">兑换记录</text>
    </Head> -->
    <view class="head">
      <image
        src="http://cdn.gtfy.net.cn/1inex/head_back_white.png"
        @click="back"
        class="back"
        mode="scaleToFill"
      />
      <text @click="toUrl('/pages/my/withdrawalList')">兑换记录</text>
    </view>

    <!-- Title 和 tip -->
    <view class="title-tip">
      <text class="title">
        {{ userobj.quota }}
        <text class="small">总资产</text>
      </text>
      <view class="tip">
        <image
          src="http://cdn.gtfy.net.cn/1inex/business/gtfy.png"
          mode="scaleToFill"
        />
        <text>兑换手续费：10% </text>
      </view>
    </view>

    <form @submit="$u.throttle(add, 3000)">
      <view class="form">
        <view class="form-item">
          <view class="label">兑换数量</view>
          <input
            class="input"
            type="number"
            placeholder="请输入10的倍数"
            v-model.number="number"
            name="number"
          />
        </view>
        <view class="form-item">
          <view class="label">银行卡</view>
          <view
            class="input"
            @click="changeBank"
          >
            <text v-if="choiceCard && choiceCard.bankNo">{{ choiceCard.bankNo }}</text>
            <navigator
              url="/pages/my/addCard"
              v-else
              >添加银行卡</navigator
            >
          </view>
        </view>
        <!-- <view class="form-item">
          <view class="label">支付密码</view>
          <input
            class="input"
            type="password"
            placeholder="请输入支付密码"
            @focus="openNumberJpan"
            readonly
            :value="payPassword"
            name="payPassword"
          />
          <NumberJpan
            :length="6"
            @closeChange="closeChange($event)"
            ref="numberPad"
          ></NumberJpan>
        </view> -->

        <view class="form-item">
          <view class="label">手机号</view>
          <input
            class="input"
            type="number"
            readonly
            disabled
            :value="userobj.phone"
            name="phone"
          />
        </view>

        <view class="form-item">
          <view class="label">验证码</view>
          <view class="code">
            <input
              class="input1"
              type="text"
              placeholder="获取验证码"
              v-model="code"
              name="code"
            />
            <CountDownBtn
              ref="countDownBtn"
              color="$price"
              @getAuthCode="handleGetCode"
            ></CountDownBtn>
          </view>
        </view>
      </view>
      <button
        class="btn"
        formType="submit"
      >
        确定
      </button>
    </form>

    <view class="prompt">
      <strong>温馨提示：</strong>
      <view class="color6">1.为保障用户资金安全，请不要频繁操作</view>
      <view class="color6">2.如提现失败，您可以尝试更换其他银行卡</view>
      <view class="color6">3.如遇问题，请联系电话客服，我们将全时为您服务</view>
    </view>
  </view>
</template>

<script>
import { cashOutAPI2 } from "@/api/my.js";
import Head from "@/components/Head/index";
import { userInfoAPI, sendCodeAPI } from "@/api/login.js";

// 表单校验
import WxValidate from "@/common/WxValidate.js";
import NumberJpan from "../../components/numberJpan/numberJpan";
import { bankList } from "@/api/bank";
import CountDownBtn from "../../components/countDownBtn/index.vue";
export default {
  components: {
    Head,
    NumberJpan,
    CountDownBtn,
  },
  data() {
    return {
      payPassword: "",
      number: "",
      userobj: {},
      time: 0,
      WxValidate: null,
      bankCardList: [],
      choiceCard: null,
      // code: "",
    };
  },
  beforeCreate: function () {},
  filters: {
    b(val) {
      if (val == "") {
        return "请选择";
      } else {
        return val;
      }
    },
  },
  onLoad() {
    //   初始化表单
    this.initValidate();

    uni.$on("handleBack", () => {
      console.log("接收到处理事件");
      this.number = "";
      this.payPassword = "";
    });
  },
  onShow() {
    // 每次打开这个页面都确保是最新的数据
    this.getInfo();

    let choiceCard = uni.getStorageSync("choiceCard") ? JSON.parse(uni.getStorageSync("choiceCard")) : false;
    if (choiceCard) {
      this.choiceCard = choiceCard;
    }
  },
  onUnload() {
    //关闭加载动画
    this.$refs.numberPad.close();
    // 不删除
    // console.log("删除缓存的选中银行卡")
    // uni.removeStorageSync("choiceCard")
  },
  methods: {
    // 处理获取验证码
    handleGetCode() {
      if (this.time == "") {
        this.time = 60;
        if (this.time > 0) {
          var interval = setInterval(function () {
            this.time--;
            if (this.time == 0) {
              clearInterval(interval);
              this.time = "";
            }
          }, 1000);
        }
        this.getVerCode();
        // 发送验证码组件开始倒计时
        this.$refs.countDownBtn.beginCountDown();
        // 设置为已发送验证码
        this.hasSend = true;
      } else {
        uni.showToast({
          title: "别着急，短信已发送",
          duration: 800,
          icon: "none",
        });
      }
    },

    getVerCode() {
      const data = {
        phone: this.userobj.phone,
      };
      sendCodeAPI(data).then((res) => {
        uni.showToast({
          title: "验证码发送成功",
          icon: "none",
          duration: 2000,
        });
      });
    },

    back() {
      uni.navigateBack();
    },
    openNumberJpan() {
      uni.hideKeyboard();
      this.$refs.numberPad.open();
    },
    closeChange(e) {
      this.payPassword = e;
    },
    initValidate() {
      // 规则
      const rules = {
        number: {
          required: true,
          number: true,
          numberParseTen: true,
        },

        // payPassword: {
        //   required: true,
        // },

        code: {
          required: true,
        },
      };
      // 提示
      const messages = {
        number: {
          required: "请输入数量",
          number: "请输入正确数量",
        },
        // payPassword: {
        //   required: "请输入支付密码",
        // },

        code: {
          required: "请输入验证码",
        },
      };
      // 校验规则
      this.WxValidate = new WxValidate(rules, messages);

      this.WxValidate.addMethod(
        "numberParseTen",
        (value, param) => {
          return value % 10 === 0;
        },
        "输入金额必须是10的倍数"
      );
    },
    /**
     * 改变银行卡
     */
    changeBank() {
      this.toUrl("/pages/my/bankCard?mode=choice");
    },

    getInfo() {
      userInfoAPI().then((res) => {
        this.userobj = res.data;
        // 改变了获取银行卡的方式,现在使用获取银行卡列表来设置银行卡
        this.getBankCard();
      });
    },
    /**
     * 获取银行卡
     */
    getBankCard() {
      bankList().then((res) => {
        this.bankCardList = res.data;
        if (Array.isArray(res) && res.length > 0) {
          this.choiceCard = this.bankCardList[0];
        } else {
          this.choiceCard = {};
        }
        let choiceCard = uni.getStorageSync("choiceCard") ? JSON.parse(uni.getStorageSync("choiceCard")) : false;
        if (choiceCard) {
          this.choiceCard = choiceCard;
        }
      });
    },
    add() {
      let params = {
        number: this.number,
        // payPassword: this.payPassword,
        code: this.code
      };
      if (!this.WxValidate.checkForm(params)) {
        const error = this.WxValidate.errorList[0];
        uni.showToast({
          title: `${error.msg}`,
          icon: "none",
        });
        return false;
      } else {
        if (!this.choiceCard || !this.choiceCard.id) {
          uni.showToast({
            title: "请添加银行卡",
            icon: "none",
          });
          return;
        }

        uni.showLoading({
          title: "提交中...",
        });

        cashOutAPI2({
          number: this.number,
          payPassword: this.payPassword,
          bankId: this.choiceCard.id,
          phone: this.userobj.phone,
          code: this.code,
        })
          .then((res) => {
            uni.hideLoading();
            this.payPassword = "";
            this.number = "";
            uni.navigateTo({
              url: "./withdrawalList",
            });
          })
          .catch((err) => {
            console.log(err);
          });
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.page {
  width: 750rpx;
  min-height: 100vh;
  background-color: #f6f6f6;

  position: relative;
  box-sizing: border-box;
  padding-top: calc(88rpx + var(--status-bar-height));

  display: flex;
  flex-flow: column nowrap;
  justify-content: flex-start;
  align-items: center;

  background-image: url(http://cdn.gtfy.net.cn/1inex/my/duihuanback.png);
  background-repeat: no-repeat;
  background-size: contain;

  .head {
    width: 750rpx;
    box-sizing: border-box;
    padding: 0 40rpx;
    height: calc(var(--status-bar-height) + 100rpx);
    line-height: 100rpx;

    padding-top: var(--status-bar-height);
    position: fixed;
    top: 0;
    left: 0;

    display: flex;
    flex-flow: row nowrap;
    justify-content: space-between;
    align-items: center;

    z-index: 2;

    color: #ffffff;
    font-size: 28rpx;

    .back {
      width: 40rpx;
      height: 30rpx;
    }
  }
  .prompt {
    width: 620rpx;
    margin-top: 80rpx;
    color: #666666;
    .color6 {
      color: #999999;
    }
  }
  .title-tip {
    width: 100%;
    height: 192rpx;

    box-sizing: border-box;
    padding: 40rpx 0;

    display: flex;
    flex-flow: column nowrap;
    justify-content: space-between;
    align-items: center;

    .title {
      height: 60rpx;
      line-height: 60rpx;
      font-size: 60rpx;
      font-family: "Microsoft YaHei", 微软雅黑, "MicrosoftJhengHei", 华文细黑, STHeiti, MingLiu;
      font-weight: bold;
      color: #ffffff;
      letter-spacing: 2rpx;

      .small {
        font-size: 24rpx;
      }
    }

    .tip {
      height: 40rpx;
      line-height: 40rpx;

      width: 100%;
      text-align: center;
      font-size: 24rpx;
      font-family: "Microsoft YaHei", 微软雅黑, "MicrosoftJhengHei", 华文细黑, STHeiti, MingLiu;
      font-weight: bold;
      color: #ffffff;

      display: flex;
      flex-flow: row nowrap;
      justify-content: center;
      align-items: center;

      image {
        width: 31rpx;
        height: 31rpx;
        margin-right: 10rpx;
      }
    }
  }

  .form {
    z-index: 2;

    width: 750rpx;
    min-height: 588rpx;

    background: #ffffff;

    box-sizing: border-box;
    padding: 40rpx;

    display: flex;
    flex-flow: column nowrap;
    justify-content: space-evenly;
    align-items: flex-start;

    .form-item {
      width: 100%;
      height: 145rpx;

      margin: 10rpx 0;

      display: flex;
      flex-flow: column nowrap;
      justify-content: space-between;
      align-items: flex-start;

      .label {
        font-size: 24rpx;
        font-family: Microsoft YaHei;
        font-weight: 400;
        color: #666666;
      }

      .input {
        width: 100%;
        height: 100rpx;
        background: #f7f7f7;
        border-radius: 50rpx;

        box-sizing: border-box;
        padding: 0 40rpx;
        font-size: 36rpx;

        line-height: 100rpx;
      }

      .code {
        width: 100%;
        display: flex;
        flex-flow: row nowrap;
        justify-content: space-between;
        align-items: center;

        .input1 {
          width: 50%;
          height: 100rpx;
          background: #f7f7f7;
          border-radius: 50rpx;

          box-sizing: border-box;
          padding: 0 40rpx;
          font-size: 36rpx;

          line-height: 100rpx;
        }
      }
    }
  }

  .btn {
    padding: 0;
    width: 630rpx;
    height: 100rpx;
    line-height: 100rpx;

    background: linear-gradient(-15deg, $price 0%, #ff5b50 100%);

    border-radius: 50rpx;

    font-size: 36rpx;
    font-family: "Microsoft YaHei", 微软雅黑, "MicrosoftJhengHei", 华文细黑, STHeiti, MingLiu;
    font-weight: bold;
    color: #ffffff;

    margin: 0 40rpx;
    margin-top: 80rpx;
  }
}
</style>
